#ifndef EDITFORMWRAPPER_H
#define EDITFORMWRAPPER_H



#include "AbstractEditFormActions.h"



#include <ItemModel.h>
#include <FileHandler.h>



#include <QWidget>
#include <QFileDialog>
#include <QTimer>



template<typename EDITFORM>
class EditFormWrapper : public EDITFORM
{
public:

    EditFormWrapper(QWidget* parent = 0)
        : EDITFORM(parent)
    {
        m_model = new ItemModel(this);
        QTimer::singleShot(0, this, SLOT(initialize()));
    }


    void open(ItemRoot* root, const QString& file_path = QString())
    {
        m_model->setRootItem(root);
        //m_filePath = file_path;

        root->setParent(this);
        root->setDirty(file_path.isEmpty());
    }



    bool save()
    {
        if (!m_model || !m_model->rootItem())
        {
            return true;
        }

        // update all appropriate
        updateData();

        ItemRoot* root = dynamic_cast<ItemRoot*>(m_model->rootItem());
        if (!root) return false;

        QString file_path = root->filePath();

        if (file_path.isEmpty() || !QFile::exists(file_path))
        {
            return saveAs();
        }

        return FileHandler::save(root, file_path);
    }


    bool saveAs()
    {
        if (!m_model || !m_model->rootItem())
        {
            return true;
        }

        QString file_path = QFileDialog::getSaveFileName(this, tr("Save File"), QDir::currentPath(), tr("Xml File (*.xml)"));
        if (file_path.isEmpty()) return true;

        ItemRoot* root = dynamic_cast<ItemRoot*>(m_model->rootItem());
        if (!root) return false;

        if (!FileHandler::save(root, file_path)) return false;
        //m_filePath = file_path;
        return true;
    }


    bool changed() const
    {
        if (!m_model || !m_model->rootItem()) return false;

        ItemRoot* root = dynamic_cast<ItemRoot*>(m_model->rootItem());
        if (!root) return false;

        return root->isDirty();
    }


protected:

    virtual ItemModel* model() const
    {
        return m_model;
    }


    //QString m_filePath;
    ItemModel* m_model;


};



#endif // EDITFORMWRAPPER_H
